package zxing.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.Icon;
import zxing.activity.adapter.IconAdapter;

public class BeautifyQRActivity extends VActivity {
    private List<Icon> iconList = new ArrayList<>();
    @BindView(R.id.head_back)
    ImageView head_back;
    @BindView(R.id.head_center_title)
    TextView head_center_title;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    IconAdapter adapter;
    String str;
    @BindView(R.id.result_img)
    ImageView result_img;
    @BindView(R.id.qr_bg)
    LinearLayout qr_bg;
    @BindView(R.id.button_bc)
    Button button_bc;

    //    icon_item
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_beautify_qr);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        str = intent.getStringExtra("data");
//        Create2QR2(str, result_img);
//        Bitmap bitmap = createQRImage(str, 300, 300);
        Bitmap mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_9bg);
        result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 180))));
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new IconAdapter(BeautifyQRActivity.this, iconList);
        recyclerView.setAdapter(adapter);
        getView();
        init();
        initAction();
    }

    public void getView() {
        head_center_title.setText("美化二维码");
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        button_bc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SaveBitmapFromView(qr_bg);
                Toast.makeText(BeautifyQRActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }
        });
    }

//    LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) result_img.getLayoutParams();

    private void getNum(int l, int t, int r, int b) {
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) result_img.getLayoutParams();
        layoutParams.setMargins(px2dip(getApplicationContext(), l), px2dip(getApplicationContext(), t), px2dip(getApplicationContext(), r), px2dip(getApplicationContext(), b));
        result_img.setLayoutParams(layoutParams);
    }

    Bitmap mask;

    protected void initAction() {
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter madapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.image_lin://整个item
                        adapter.setsele(position);
                        switch (position) {
                            case 0:
                                getNum(0, 0, 0, 0);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        (px2dip(getApplicationContext(), 150)),
                                        getResources().getColor(R.color.black),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_1bg);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 1:
                                getNum(0, 25, 0, 0);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        (px2dip(getApplicationContext(), 150)),
                                        getResources().getColor(R.color.black),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_5bg);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 2:
                                getNum(0, 0, 0, 0);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        px2dip(getApplicationContext(), 150),
                                        getResources().getColor(R.color.black),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_6bg);
                                qr_bg.setPadding(210, 210, 210, 210);

                                break;
                            case 3:
                                getNum(0, 45, 0, 0);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        (px2dip(getApplicationContext(), 120)),
                                        getResources().getColor(R.color.black),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_7bg);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 4:
                                getNum(0, 0, 0, 0);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        (px2dip(getApplicationContext(), 150)),
                                        getResources().getColor(R.color.holo_red),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_8bg);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 5:
                                getNum(0, 40, 0, 0);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        (px2dip(getApplicationContext(), 100)),
                                        getResources().getColor(R.color.colo6),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erwiema_10bg);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 6:
                                getNum(5, 0, 0, 45);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmapClors(
                                        str,
                                        (px2dip(getApplicationContext(), 94)),
                                        getResources().getColor(R.color.black),
                                        getResources().getColor(R.color.white)));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_20bg);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 7://juxingerweima_9
                                getNum(0, 28, 1, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_2bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 172)), mask));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_2bg1);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 8://juxingerweima_9
                                getNum(13, 0, 0, 8);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_9bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 152)), mask));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_9bg1);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 9:
                                getNum(0, 0, 19, 10);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_3bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 112)), mask));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_3bg1);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 10:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_12bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 11:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_13bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 12:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_14bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 13:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_15bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 14:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_16bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 15:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_17bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 16:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_18bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 17:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_19bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 18:
                                getNum(0, 0, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erwiema_11bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 150)), mask));
                                qr_bg.setBackgroundColor(getResources().getColor(R.color.white));
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            case 19:
                                getNum(0, 30, 0, 0);
                                mask = BitmapFactory.decodeResource(getResources(), R.mipmap.erweima_4bg);
                                result_img.setImageBitmap(QRCodeUtil.createQRCodeBitmap(str, (px2dip(getApplicationContext(), 165)), mask));
                                qr_bg.setBackgroundResource(R.mipmap.erweima_4bg1);
                                qr_bg.setPadding(0, 0, 0, 0);
                                break;
                            default:
                                break;
                        }//
                        break;
                    default:
                        break;
                }
            }
        });
    }

    public static int px2dip(Context context, int dp) {
        float density = context.getResources().getDisplayMetrics().density;
        return (int) (dp * density + 0.5);

    }


    private void init() {
        Icon a = new Icon(R.mipmap.juxingerweima_1);
        iconList.add(a);
        Icon b = new Icon(R.mipmap.juxingerweima_5);
        iconList.add(b);
        Icon c = new Icon(R.mipmap.juxingerweima_6);
        iconList.add(c);
        Icon d = new Icon(R.mipmap.juxingerweima_7);
        iconList.add(d);
        Icon e = new Icon(R.mipmap.juxingerweima_8);
        iconList.add(e);
        Icon f = new Icon(R.mipmap.juxingerweima_10);//
        iconList.add(f);
        Icon g = new Icon(R.mipmap.juxingerweima_20);
        iconList.add(g);
        Icon h = new Icon(R.mipmap.juxingerweima_2);
        iconList.add(h);
        Icon i = new Icon(R.mipmap.juxingerweima_9);
        iconList.add(i);
        Icon j = new Icon(R.mipmap.juxingerweima_3);
        iconList.add(j);
        Icon k = new Icon(R.mipmap.juxingerweima_12);
        iconList.add(k);
        Icon l = new Icon(R.mipmap.juxingerweima_13);
        iconList.add(l);
        Icon m = new Icon(R.mipmap.juxingerweima_14);
        iconList.add(m);
        Icon n = new Icon(R.mipmap.juxingerweima_15);
        iconList.add(n);
        Icon o = new Icon(R.mipmap.juxingerweima_16);
        iconList.add(o);
        Icon p = new Icon(R.mipmap.juxingerweima_17);
        iconList.add(p);
        Icon q = new Icon(R.mipmap.juxingerweima_18);
        iconList.add(q);
        Icon r = new Icon(R.mipmap.juxingerweima_19);
        iconList.add(r);
        Icon s = new Icon(R.mipmap.juxingerweima_11);
        iconList.add(s);
        Icon t = new Icon(R.mipmap.juxingerweima_4);
        iconList.add(t);
    }

    public Bitmap SaveBitmapFromView(View view) {
        int w = view.getWidth();
        int h = view.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
//        view.layout(0, 0, w, h);
        c.drawColor(Color.WHITE);
        view.draw(c);
        // 缩小图片
        Matrix matrix = new Matrix();
        matrix.postScale(0.5f, 0.5f); //长和宽放大缩小的比例

        bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
//获取当前时间
        Date date = new Date(System.currentTimeMillis());
//        saveBitmap(bmp, simpleDateFormat.format(date) + ".jpg");
        String str = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + simpleDateFormat.format(date) + ".jpg";

        boolean save = ImageUtils.save(bmp, str, Bitmap.CompressFormat.JPEG);
//        ToastUtils.showLong(save ? "保存成功" : "保存失败");
        if (save) {
            String copyFilePath  ;
            if (Build.BRAND.equals("Xiaomi")) { // 小米手机
//            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
                copyFilePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + TimeUtils.getNowMills() + ".jpg";
            } else {  // Meizu 、Oppo
//                str = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + simpleDateFormat.format(date) + ".jpg";
                copyFilePath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + TimeUtils.getNowMills() + ".jpg";
//            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
            }
            if (FileUtils.copyFile(str,copyFilePath)) {
                FileUtils.delete(str);
            }
            MediaScannerConnection.scanFile(BeautifyQRActivity.this, new String[]{copyFilePath}, null, null);

        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
//                CodeDisplayActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + str)));
//                MediaScannerConnection.scanFile(CodeDisplayActivity.this, new String[]{str}, null, null);
            }
        }, 500);

        return bmp;
    }

    /*
     * 保存文件，文件名为当前日期
     */
    public void saveBitmap(Bitmap bitmap, String bitName) {
        String fileName;
        File file;
        if (Build.BRAND.equals("Xiaomi")) { // 小米手机
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + bitName;
        } else {  // Meizu 、Oppo
            fileName = Environment.getExternalStorageDirectory().getPath() + "/DCIM/" + bitName;
        }
        file = new File(fileName);

        if (file.exists()) {
            file.delete();
        }
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            // 格式为 JPEG，照相机拍出的图片为JPEG格式的，PNG格式的不能显示在相册中
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
                out.flush();
                out.close();
// 插入图库
                MediaStore.Images.Media.insertImage(this.getContentResolver(), file.getAbsolutePath(), bitName, null);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        // 发送广播，通知刷新图库的显示
        this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + fileName)));

    }

}
